package com.pxmeta.app.controller.game;


import cn.dev33.satoken.annotation.SaCheckLogin;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.core.redis.RedisCache;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.dynamic.service.RedisLockService;
import com.pxmeta.party.entity.*;
import com.pxmeta.party.entity.dto.ActivityAdAstraDTO;
import com.pxmeta.party.entity.dto.AdAstraConfirmDispatchDTO;
import com.pxmeta.party.entity.vo.*;
import com.pxmeta.party.service.*;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/activity-ad-astra")
@Api(value = "派对活动-星际探险",tags = "派对活动-星际探险")
@RequiredArgsConstructor
@CrossOrigin
public class ActivityAdAstraController {
    private final IActivityAdAstraService activityAdAstraService;
    private final IActivityAdAstraRecordService activityAdAstraRecordService;
    private final IActivityAdAstraUserRecordService activityAdAstraUserRecordService;
    private final IUserService userService;
    private final RedisCache redisCache;
    private final RedisLockService redisLockService;

    private final IGiftService giftService;


    @SaCheckLogin
    @GetMapping("/getShipCount")
    @ApiOperation("获取飞船数量")
    public AjaxResult getShipCount(){
        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        Integer adAstraBalance = user.getAdAstraBalance();
        Map<String, Object> map = Maps.newHashMap();
        map.put("shipCount", adAstraBalance);
        return AjaxResult.success(map);
    }


    @GetMapping("/getDataList")
    @ApiOperation("获取数据链接")
    public AjaxResult getDataList(@RequestParam Integer page,
                                  @RequestParam Integer size){
        List<ActivityAdAstraDataHistoryVO> list = activityAdAstraService.getDataList(page,size);
        return AjaxResult.success(list);
    }


    @GetMapping("/getStarOverdueCount")
    @ApiOperation("获取星球逾期数")
    public AjaxResult getStarOverdueCount(){
        List<ActivityAdAstra> list = activityAdAstraService.getStarOverdueCount();
        return AjaxResult.success(list);
    }

    @GetMapping("/getDataStatistics")
    @ApiOperation("获取数据统计")
    public AjaxResult getDataStatistics(){
        List<ActivityAdAstraDataStatisticsVO> list = activityAdAstraService.getDataStatistics();
        return AjaxResult.success(list);
    }

    @GetMapping("/getDataStatisticsDetail")
    @ApiOperation("获取数据统计详情")
    public AjaxResult getDataStatisticsDetail(@RequestParam Long id){
        List<ActivityAdAstraDataStatisticsItemVO> list = activityAdAstraService.getDataStatisticsDetail(id);
        return AjaxResult.success(list);
    }

    @GetMapping("/getLateCountList")
    @ApiOperation("获取晚点数量列表")
    public AjaxResult getLateCountList(){
        ActivityAdAstraDataLateVO list = activityAdAstraRecordService.getLateCountList();
        return AjaxResult.success(list);
    }

    @GetMapping("/getHistoryDataItemList")
    @ApiOperation("获取历史数据明细")
    public AjaxResult getHistoryDataItemList(@RequestParam Long recordId){
        List<ActivityAdAstraUserRecord> records = activityAdAstraUserRecordService.getByRecordId(recordId);
        records = records.stream().filter(r->r.getStatus() == 1).collect(Collectors.toList());
        List<ActivityAdAstraUserRankingVO> finalList = Lists.newLinkedList();
        if (!records.isEmpty()){

            for (ActivityAdAstraUserRecord record : records) {
                Long userId = record.getUserId();
                User user = userService.getById(userId);
                ActivityAdAstraUserRankingVO vo = new ActivityAdAstraUserRankingVO();
                List<Gift> giftList = giftService.spendCoins(record.getRewardPrice(), 11, 625000, 500000, 100000, 10000, 2500);
                List<ActivityAdAstraDispatchGiftVO> gifts = Lists.newLinkedList();
                for (Gift gift : giftList) {

                    Boolean isContains = Boolean.FALSE;
                    for (ActivityAdAstraDispatchGiftVO giftVO : gifts) {
                        if (gift.getId().equals(giftVO.getId())) {
                            giftVO.setCount(giftVO.getCount() + 1);
                            isContains = Boolean.TRUE;
                            break;
                        }
                    }

                    if (isContains) {
                        continue;
                    }

                    ActivityAdAstraDispatchGiftVO giftVO = new ActivityAdAstraDispatchGiftVO();
                    giftVO.setCount(1);
                    giftVO.setName(gift.getName());
                    giftVO.setIcon(gift.getIcon());
                    giftVO.setPrice(gift.getPrice());
                    giftVO.setId(gift.getId());
                    gifts.add(giftVO);
                }
                vo.setGiftList(gifts);
                vo.setNickname(user.getNickname());
                vo.setAvatar(user.getAvatar());
                vo.setPrice(record.getRewardPrice());
                finalList.add(vo);
            }
        }


        return AjaxResult.success(finalList);
    }


    @SaCheckLogin
    @PostMapping("/buyShip")
    @ApiOperation("购买飞船")
    public AjaxResult buyShip(@RequestParam Integer count,
                              @RequestParam String partyId){
        Long userId = SecurityUtils.getUserId();
        activityAdAstraService.buyShip(userId,count,partyId);
        return AjaxResult.success();
    }

    @GetMapping("/getEndTime")
    @ApiOperation("获取截止时间")
    @CrossOrigin
    public AjaxResult getEndTime(){
        Long endTimeMillis = redisCache.getCacheObject("countdown_time");
        Map<String, Object> map = Maps.newHashMap();
        map.put("endTimeMillis", endTimeMillis);
        return AjaxResult.success(map);
    }


    @GetMapping("/getDispatchRecord")
    @SaCheckLogin
    @ApiOperation("获取派遣记录")
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "type", value = "类型: 1派遣记录，2探险日志"),
            }
    )
    public AjaxResult getDispatchRecord(@RequestParam Integer type){

        Long userId = SecurityUtils.getUserId();
        List<ActivityAdAstraRecordVO> list = activityAdAstraRecordService.getDispatchRecord(userId, type);
        return AjaxResult.success(list);
    }


    @GetMapping("/getStarList")
    @SaCheckLogin
    @ApiOperation("获取星球列表")
    public AjaxResult getStarList(){
        Long userId = SecurityUtils.getUserId();
        List<ActivityAdAstra> list = activityAdAstraService.getStarList(userId);
        return AjaxResult.success(list);
    }

    @SaCheckLogin
    @PostMapping("/confirmDispatch")
    @ApiOperation("确认派遣")
    public AjaxResult confirmDispatch(@RequestBody AdAstraConfirmDispatchDTO dto){
        Long userId = SecurityUtils.getUserId();

        int minute = LocalDateTime.now().getMinute();
        if (minute>50){
            return AjaxResult.error("本轮派遣已终止，请等待下一轮！");
        }
        String key = userId + "_confirmDispatch";
        String lock = redisLockService.lock(key, 1000, 200);
        if (StringUtils.isNotBlank(lock)){
            ActivityAdAstra success = activityAdAstraService.confirmDispatch(userId, dto.getList());
            List<ActivityAdAstraDTO> dtoList = dto.getList();
            HashMap<String, Object> map = Maps.newHashMap();
            map.put("success", success);
            List<Long> ids = dtoList.stream().map(ActivityAdAstraDTO::getId).collect(Collectors.toList());
            if (ids.contains(success.getId())){
                map.put("isSuccess",Boolean.TRUE);
            }else {
                map.put("isSuccess",Boolean.FALSE);
            }
            return AjaxResult.success(map);
        }
        return AjaxResult.error("请勿重复派遣！");
    }

    @GetMapping("/getDispatchResult")
    @ApiOperation("获取派遣结果")
    @SaCheckLogin
    public AjaxResult<ActivityAdAstraDispatchResultVO> getDispatchResult(){
        Long userId = SecurityUtils.getUserId();
        ActivityAdAstraDispatchResultVO vo = activityAdAstraRecordService.getDispatchStatus(userId);
        return AjaxResult.success(vo);

    }


    @SaCheckLogin
    @GetMapping("/getUserRanking")
    @ApiOperation("获取用户榜单")
    public AjaxResult<List<ActivityAdAstraUserRankingVO>> getUserRanking(@RequestParam Integer page,
                                     @RequestParam Integer size){
        List<ActivityAdAstraUserRankingVO> list = activityAdAstraRecordService.getUserRanking(page,size);
        return AjaxResult.success(list);
    }




}
